package org.unicorn.android.base

import android.app.Application
import androidx.activity.ComponentActivity
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider

/**
 *
 * @author     : liujianyou
 * @date : 2022/02/16 17:40
 * @Description:
 */
inline fun <reified T : ViewModel> Application.viewModels(): Lazy<T> = lazy {
    return@lazy ViewModelProvider.AndroidViewModelFactory(this).create(T::class.java)
}

inline fun <reified T : ViewModel> ComponentActivity.viewModels(): Lazy<T> = lazy {
    return@lazy ViewModelProvider(
        viewModelStore,
        ViewModelProvider.AndroidViewModelFactory(application)
    )[T::class.java]
}


inline fun <reified T : ViewModel> Fragment.viewModels(): Lazy<T> = lazy {
    return@lazy ViewModelProvider(
        viewModelStore,
        ViewModelProvider.AndroidViewModelFactory(requireContext().applicationContext as Application)
    )[T::class.java]
}

inline fun <reified T : ViewModel> Fragment.activityViewModels(): Lazy<T> = lazy {
    return@lazy ViewModelProvider(
        (activity as ComponentActivity).viewModelStore,
        ViewModelProvider.AndroidViewModelFactory(requireContext().applicationContext as Application)
    )[T::class.java]
}